﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
public partial class JobManage_CompanyJobDetail : BasePage
{
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    IJobHandler jobManage = new JobHandler();
    IBNTruckHandler truckManage = new BNTruckHandler();
    ISystemHandler systemManage = new SystemHandler();
    ISendTruckHandler sendTruckManage = new SendTruckHandler();
    ISyContainerModelHandler containerModelManage = new SyContainerModelHandler();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1060")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
                    if (strPermission.Contains("1073"))
                    {
                        if (orderQuery != null)
                        {
                            if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CONFIM.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.PRINT.ToString("d"))
                            {
                                btnCancel.Visible = true;
                            }
                            else
                            {
                                btnCancel.Visible = false;
                            }
                        }

                    }
                    else
                    {
                        btnCancel.Visible = false;
                    }

                    if (strPermission.Contains("1065"))
                    {
                        if (orderQuery != null)
                        {
                            if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d"))
                            {
                                btnConfirm.Visible = true;
                            }
                            else
                            {
                                btnConfirm.Visible = false;
                            }
                        }

                    }
                    else
                    {
                        btnConfirm.Visible = false;
                    }
                }

                ViewState["OrderBy"] = "PKID";
                ViewState["Accending"] = "desc";

                ViewState["OrderByT"] = "PKID";
                ViewState["AccendingT"] = "desc";
                dataBind();
            }
        }
    }

    public string GetClient(object id)
    {
        return systemManage.GetClient(id);
    }

    public string GetUserName(object userID)
    {
        return systemManage.GetUserName(userID);
    }

    public string GetDriver(object id)
    {
        return systemManage.GetDriver(id);
    }

    public string GetType(object typeID)
    {
        string model=string.Empty;
        Sy_ContainerModelQuery query = containerModelManage.GetModel(int.Parse(typeID.ToString()));
        if (query != null)
        {
            return model = query.Model;
        }
        return model;
    }

    private void dataBind()
    {
        if (Request["OrderID"] != null)
        {
            BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
            if (orderQuery != null)
            {
                //txtOrderNO.Text = orderQuery.OrderNO;
                txtBookingNO.Text = orderQuery.BookingNO;
                if (orderQuery.BookingDate != DateTime.MinValue)
                {
                    txtBookingDate.Text = orderQuery.BookingDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                txtStatus.Text = StringUtil.GetShipperOrderStatus(orderQuery.Status);
                txtVendor.Text = GetClient(orderQuery.VendorID);
                txtArrangeUser.Text = GetUserName(orderQuery.ArrangeUser);
                if (orderQuery.ArrangeDate != DateTime.MinValue)
                {
                    txtArrangeDate.Text = orderQuery.ArrangeDate.ToString("yyyy-MM-dd HH:mm:ss");
                }

                if (orderQuery.CheckDate != DateTime.MinValue)
                {
                    txtCheckDate.Text = orderQuery.CheckDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                txtCheckUser.Text = GetUserName(orderQuery.CheckUser);

                if (orderQuery.ConfirmDate != DateTime.MinValue)
                {
                    txtConfimDate.Text = orderQuery.ConfirmDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                txtConfimUser.Text = GetUserName(orderQuery.ConfirmUser);

                if (orderQuery.PrintDate != DateTime.MinValue)
                {
                    txtPrintDate.Text = orderQuery.PrintDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                txtPrintUser.Text = GetUserName(orderQuery.PrintUser);

                if (orderQuery.CancelDate != DateTime.MinValue)
                {
                    txtCancelDate.Text = orderQuery.CancelDate.ToString("yyyy-MM-dd HH:mm:ss");
                }

                txtCancelUser.Text = GetUserName(orderQuery.CancelUser);

                if (orderQuery.CancelConfirmDate != DateTime.MinValue)
                {
                    txtCancelConfirmDate.Text = orderQuery.CancelConfirmDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                txtCancelConfirmUser.Text = GetUserName(orderQuery.CancelConfirmUser);

                if (orderQuery.CancelArrDate != DateTime.MinValue)
                {
                    txtCancelArrDate.Text = orderQuery.CancelArrDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                txtCancelArrangeUser.Text = GetUserName(orderQuery.CancelArrangeUser);

                if (orderQuery.MateReceiptDate != DateTime.MinValue)
                {
                    txtMateReceiptDate.Text = orderQuery.MateReceiptDate.ToString("yyyy-MM-dd HH:mm:ss");
                }
                txtMateReceiptConfirmUser.Text = GetUserName(orderQuery.MateReceiptConfirmUser);

                txtAppointment.Text = orderQuery.Appointament;

                txtRemark.Text = orderQuery.Remark;

                dataBindDetail(orderQuery.PKID);
                dataBindTruck(GetClientID());
            }
        }
    }

    private void dataBindDetail(int orderID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@OrderID", orderID.ToString());
        string sqlStr = "select * from BN_ShippingOrderDtl where OrderID=@OrderID";
        DataTable dt = jobManage.GetShippingOrderDtl(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        gvShipperOrderDetailList.DataSource = view;
        gvShipperOrderDetailList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }

    private void dataBindTruck(int clientID)
    {
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@OrderID", Request["OrderID"]);
        string sqlStr = @"select *,LicenseNO,(select Name from BN_Driver as T where T.PKID=BTDtl.Driver) as DriverName,
            (select CNShortName from Sy_Client as SC where SC.PKID=BT.Contractor) as ContractorName,
            (select Model from Sy_ContainerModel as m where m.PKID =BTDtl.TypeID) as TypeName,
            (select OrderNO from BN_ShippingOrder as SO where SO.PKID=BT.OrderID) as OrderNO 
            from BN_SendTruck as BT,BN_SendTruckDtl as BTDtl,BN_Truck as T where BT.PKID=BTDtl.SendTruckID and T.PKID =BTDtl.TruckID and BT.OrderID=@OrderID";
        DataTable dt = sendTruckManage.GetList(sqlStr, parms);
        gvTruckList.DataSource = dt;
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderByT"] + " " + ViewState["AccendingT"];
        gvTruckList.DataSource = view;
        gvTruckList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotalTruck.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotalTruck.Text = "0";
        }
    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvShipperOrderDetailList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvShipperOrderDetailList.PageCount)
            {
                this.gvShipperOrderDetailList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);
                return;
            }
        }
        catch
        {
            // Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
            Jscript.Alert(Resources.Messages.WrongPageNumInput, this.Page);

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvShipperOrderDetailList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBindDetail(int.Parse(Request["OrderID"]));
    }


    protected void gvShipperOrderDetailList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvShipperOrderDetailList.PageIndex = e.NewPageIndex;
        dataBindDetail(int.Parse(Request["OrderID"]));
    }
    protected void gvShipperOrderDetailList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBindDetail(int.Parse(Request["OrderID"]));
    }

    protected void lbtnGoTruck_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvTruckList.BottomPagerRow.FindControl("txtPagesTruck"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvTruckList.PageCount)
            {
                this.gvShipperOrderDetailList.PageIndex = i;
                //数据绑定
                dataBindTruck(GetClientID());
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);

        }
    }
    protected void ddlPagesTruck_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvTruckList.PageSize = int.Parse(ddlPagesTruck.SelectedValue);
        dataBindTruck(GetClientID());
    }

    protected void gvTruckList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvTruckList.PageIndex = e.NewPageIndex;
        dataBindTruck(GetClientID());
    }
    protected void gvTruckList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderByT"].ToString().ToLower())
        {
            if (ViewState["AccendingT"].ToString().ToLower() == "asc")
            {
                ViewState["AccendingT"] = "desc";
            }
            else
            {
                ViewState["AccendingT"] = "asc";
            }
        }
        else
        {
            ViewState["OrderByT"] = e.SortExpression;
        }

        dataBindTruck(GetClientID());
    }

    private int GetClientID()
    {
        int clientID = 0;
        if (Session["UserID"] != null)
        {
            UsersQuery query = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
            if (query != null)
            {
                clientID = query.ClientID;
            }
        }
        return clientID;
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (Request["OrderID"] != null)
        {
            BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
            if (orderQuery != null)
            {
                if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CONFIM.ToString("d") || orderQuery.Status.ToString() == Enums.ShippingOrderStatus.PRINT.ToString("d"))
                {
                    SqlParameter[] parms = new SqlParameter[5];
                    parms[0] = new SqlParameter("@Status", Enums.ShippingOrderStatus.CANCELCONFIM.ToString("d"));
                    parms[1] = new SqlParameter("@CancelConfirmUser", Session["UserID"].ToString());
                    parms[2] = new SqlParameter("@CancelConfirmDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd"));
                    parms[3] = new SqlParameter("@OrderID", Request["OrderID"]);
                    parms[4] = new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.COCANCEL.ToString("d"));//BookingNoteDtl 公司取消确认job状态
                    string sqlStr = "update BN_ShippingOrder set Status=@Status,CancelConfirmUser=@CancelConfirmUser,CancelConfirmDate=@CancelConfirmDate where PKID=@OrderID;";
                    sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,CancelConfirmDate=@CancelConfirmDate,CancelConfirmUser=@CancelConfirmUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID));";

                    if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.CanceledConfirmJobSuccess, "CompanyManageJobList.aspx", UpdatePanel1);
                    }
                    else
                    {
                        Jscript.AlertInAjax(Resources.Messages.CanceledConfirmJobFailed, UpdatePanel1);
                    }
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.JobCancelConfirm, UpdatePanel1);
                    return;
                }
            }
        }
    }

    protected void btnConfirm_Click(object sender,EventArgs e)
    {
        if (Request["OrderID"] != null)
        {
            BN_ShippingOrderQuery orderQuery = jobManage.GetShippingOrderByID(int.Parse(Request["OrderID"]));
            if (orderQuery != null)
            {
                if (orderQuery.Status.ToString() == Enums.ShippingOrderStatus.CHECK.ToString("d"))
                {
                    SqlParameter[] parms = new SqlParameter[6];
                    parms[0] = new SqlParameter("@Status", Enums.ShippingOrderStatus.CONFIM.ToString("d"));//ShippingOrder 公司确认状态
                    parms[1] = new SqlParameter("@ConfirmUser", Session["UserID"].ToString());
                    parms[2] = new SqlParameter("@ConfirmDate", DateTime.Now.ToString("yyyy-MM-dd HH:mm:dd"));
                    parms[3] = new SqlParameter("@OrderID", Request["OrderID"]);
                    //parms[4] = new SqlParameter("@BookingStatus",Enums.BookingStatus.CONFIRM.ToString("d"));
                    parms[4] = new SqlParameter("@BookingID",orderQuery.BookingID.ToString());
                    parms[5] = new SqlParameter("@BookingNoteDtlStatus", Enums.BookingNoteDtlStatus.CONFIRMBOOKING.ToString("d"));//BookingNoteDtl 公司确认job状态
                    string sqlStr = "update BN_ShippingOrder set Status=@Status,ConfirmUser=@ConfirmUser,ConfirmDate=@ConfirmDate where PKID=@OrderID;";
                    //sqlStr += "update BN_Booking set CBDate=@ConfirmDate,CBUser=@ConfirmUser where PKID=@BookingID;";
                    sqlStr += "update BN_BookingNoteDtl set Status=@BookingNoteDtlStatus,CBDate=@ConfirmDate,CBUser=@ConfirmUser where PKID in(select BookingNoteDtlID from BN_BookingDtl where PKID in(select BookingDtlID from BN_ShippingOrderDtl where OrderID=@OrderID));";
                    if (jobManage.ShippingOrderUpdate(sqlStr, parms))
                    {
                        Jscript.AlertAndRedirectInAjax(Resources.Messages.CompanyConfirmJobSuccess, "CompanyManageJobList.aspx", UpdatePanel1);
                    }
                    else
                    {
                        Jscript.AlertInAjax(Resources.Messages.CompanyConfirmJobFailed, UpdatePanel1);
                    }
                }
                else
                {
                    Jscript.AlertInAjax(Resources.Messages.JobConfirm, UpdatePanel1);
                    return;
                }
            }
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("CompanyManageJobList.aspx");
    }


}
